<template>
  <div>
    <el-dialog
      :title="title"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="cancelDialog"
      width="730px"
      top="50px"
    >
      <el-form ref="customerInput" v-loading="loading" class="gl_form_mini" size="small" :model="customerInput" style="padding: 0 30px" :rules="customerInput_rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学员姓名" prop="name">
              <el-input v-if="!isCheck" v-model="customerInput.name" maxlength="10" placeholder="请输入学员姓名" oninput="if(value.length > 10) value.substring(0, 10)" type="text" size="mini" />
              <span v-else>{{ customerInput.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="证件号码" prop="idCardTypeCode">
              <el-select v-if="!isCheck" v-model="customerInput.idCardTypeCode" size="mini">
                <el-option v-for="item in dict.idCardType" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else>{{ customerInput.idCardTypeCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label-width="0px" prop="idCardNumber" :rules="customerInput.idCardTypeCode === 'IdCard' ? customerInput_rules.idCard : {}">
              <el-input v-if="!isCheck" v-model="customerInput.idCardNumber" placeholder="请输入证件号码" maxlength="30" type="text" size="mini" />
              <span v-else>{{ customerInput.idCardNumber }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="国籍" prop="nationality">
              <el-select v-if="!isCheck" v-model="customerInput.nationality" placeholder="请选择国籍" filterable size="mini" style="width: 100%" @change="onChangeNationality">
                <el-option v-for="item in dict.country" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else><span v-for="item in dict.country" :key="item.code">{{ item.code === customerInput.nationality ? item.value : '' }}</span></span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="national">
              <el-select v-if="!isCheck" v-model="customerInput.national" placeholder="请选择民族" size="mini" style="width: 100%">
                <el-option v-for="item in filterNationDict" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else><span v-for="item in filterNationDict" :key="item.code">{{ item.code === customerInput.national ? item.value : '' }}</span></span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="电话号码" prop="contactTypeCode">
              <el-select v-if="!isCheck" v-model="customerInput.contactTypeCode" placeholder="请选择联系人与本人关系" size="mini">
                <el-option v-for="item in dict.contactType" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else>{{ customerInput.contactTypeCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label-width="0px" prop="phoneNumber">
              <el-input v-if="!isCheck" v-model="customerInput.phoneNumber" placeholder="请输入电话号码" type="text" size="mini" />
              <span v-else>{{ customerInput.phoneNumber }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="genderCode">
              <el-select v-if="!isCheck" v-model="customerInput.genderCode" size="mini" style="width:100%">
                <el-option key="M" label="男" value="M" />
                <el-option key="W" label="女" value="W" />
              </el-select>
              <span v-else>{{ customerInput.genderCode }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="微信" prop="wxAccount">
              <el-input v-if="!isCheck" v-model="customerInput.wxAccount" placeholder="请输入微信号" maxlength="30" type="text" size="mini" />
              <span v-else>{{ customerInput.wxAccount }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="学员地址" prop="address">
          <el-input v-if="!isCheck" v-model="customerInput.address" placeholder="请输入学员地址" maxlength="16" size="mini" type="text" />
          <span v-else>{{ customerInput.address }}</span>
        </el-form-item>

        <el-form-item label="头像" prop="imagePath">
          <el-input v-show="false" v-model.trim="customerInput.imagePath" />
          <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
            <photo-cropper ref="photoCropper" :photograph="false" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
          </el-dialog>
          <div v-if="!isCheck" class="upload_game_img" @click="openPhotoCropper">
            <img v-if="customerInput.imagePath" class="show_img" :src="getStaticPhotoUrl(customerInput.imagePath)">
            <i v-else class="el-icon-plus" />
          </div>
          <div v-else class="upload_game_img">
            <img v-if="customerInput.imagePath" class="show_img" :src="getStaticPhotoUrl(customerInput.imagePath)">
          </div>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="来源渠道" prop="customerSourceId">
              <el-cascader v-if="!isCheck" v-model="customerInput.customerSource" size="mini" :show-all-levels="false" :options="groupList" :props="{ value: 'id', label: 'name' }" placeholder="请选择来源渠道" style="width: 100%;" />
              <span v-else>{{ customerInput.customerSourceId }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="意向度" prop="intentionDegreeCode">
              <el-select v-if="!isCheck" v-model="customerInput.intentionDegreeCode" size="mini" style="width: 100%">
                <el-option v-for="item in dict.intentionDegreeType" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else>{{ customerInput.intentionDegreeTypeCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="customerTagId">
              <el-select v-if="!isCheck" v-model="customerInput.customerTagId" size="mini" style="width: 100%">
                <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <span v-else>{{ customerInput.customerTagId }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item v-if="hasFollow || isCheck" label="跟进人" prop="followUpEmployeeId">
              <div v-if="!isCheck">
                <el-tag v-if="customerInput.followUpName" closable style="margin-right:10px" @close="closeSource()">{{ customerInput.followUpName }}</el-tag>
                <el-button size="mini" icon="el-icon-circle-plus-outline" @click="openDialog()" />
              </div>
              <span v-else>{{ customerInput.followUpEmployeeId }}</span>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelDialog">取消</el-button>
        <el-button v-if="!isCheck" type="primary" :loading="btnLoading" size="mini" @click="submit()">确 定</el-button>
        <el-button v-else type="primary" size="mini" @click="cancelDialog()">确 定</el-button>
      </span>
    </el-dialog>

    <add-follow ref="addFollow" />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import addFollow from './addFollowUp.vue';
import photoCropper from '@/components/PhotoCropper';
import validator from '@/lib/validate/index.js';
import {
  SaveCustomerInput, // 创建客户信息
  Api_GET_ClubCustomerSourceGroupQO, // 分页获取分组信息
  Api_GET_ClubCustomerSourceQO, // 分页获取来源信息
  Api_GET_ClubCustomerTagQO // 分页获取客户标签信息
} from '@/lib/form/hall/swaggerForm';
import {
  api_GET_ClubCustomerTag, // 分页获取客户标签信息
  api_GET_ClubCustomerSourceGroup, // 分页获取分组信息
  api_GET_ClubCustomerSource // 分页获取来源信息
} from '@/extend/api/hallswaggerApi/app';
export default {
  components: { photoCropper, addFollow },
  props: {
    hasFollow: { // 是否需要跟进人
      type: Boolean,
      required: false,
      default: false
    },
    employeeid: { // 我的员工ID
      type: String,
      required: false,
      default: ''
    },
    title: { // 弹窗标题
      type: String,
      required: false,
      default: '添加客户'
    },
    isCheck: { // 查看
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperOption: {
        img: '',
        autoCropWidth: '200px',
        autoCropHeight: '280px',
        enlarge: 1,
        fixedNumber: [200, 280]
      },
      id: '',
      followUp: {}, // 跟进人
      groupList: [],
      sourceList: [],
      labelList: [],
      loading: false,
      btnLoading: false,
      dialogVisible: false,
      customerInput: new SaveCustomerInput(),
      filterNationDict: [],
      customerInput_rules: {
        name: [{ required: true, message: '学员姓名不能为空', trigger: 'blur' }],
        idCard: [
          {
            validator(rule, value, callback) {
              callback(validator.checkIdNumber(value, '身份证号码格式错误'));
            },
            trigger: 'blur'
          }
        ],
        unIdCard: [
          { required: true, message: '请输入证件号码', trigger: 'blur' }
        ],
        contactTypeCode: [{ required: true, message: '与本人关系不能为空', trigger: 'blur' }],
        genderCode: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        phoneNumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              callback(validator.checkPhone(value, '手机号码格式错误'));
            },
            trigger: 'blur'
          }
        ],
        customerSourceId: [{ required: true, message: '来源渠道不能为空', trigger: 'blur' }]
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    'customerInput.nationality': {
      deep: true,
      immediate: true,
      handler (val) {
        // 中国国籍，民族显示56个民族及外国血统中国人士
        if (val === 'CHN') {
          // 57 表示其他
          this.filterNationDict = this.dict.nation.filter(item => item.code !== '57');
        } else {
          this.filterNationDict = [{ code: '57', value: '其他' }];
        }
      }
    }
  },
  created() {
    this.getDict();
    this.getLabel();
    this.getGroup();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    getGroup() {
      const qo = new Api_GET_ClubCustomerSourceGroupQO();
      qo.MaxResultCount = 999;
      api_GET_ClubCustomerSourceGroup(qo).then(res => {
        this.groupList = res.items;
        this.groupList = this.groupList.map(item => {
          return { 'name': item.name, 'id': item.id, 'children': [] };
        });
        this.getSource();
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    getSource() {
      const that = this;
      const qo = new Api_GET_ClubCustomerSourceQO();
      qo.IncludeSourceGroup = true;
      qo.MaxResultCount = 999;
      api_GET_ClubCustomerSource(qo).then(res => {
        this.sourceList = res.items;
        this.sourceList.map(item => {
          const index = that.groupList.findIndex(jtem => jtem.id === item.sourceGroup.id);
          that.groupList[index].children.push({ 'name': item.name, 'id': item.id });
        });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    getLabel() {
      const qo = new Api_GET_ClubCustomerTagQO();
      qo.MaxResultCount = 999;
      api_GET_ClubCustomerTag(qo).then(res => {
        this.labelList = res.items;
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    submit() {
      if (this.customerInput.idCardNumber) {
        this.customerInput_rules.idCardTypeCode ? '' : this.$set(this.customerInput_rules, 'idCardTypeCode', [{ required: true, message: '请选择证件类型', trigger: 'change' }]);
      } else {
        this.customerInput_rules.idCardTypeCode ? delete this.customerInput_rules.idCardTypeCode : '';
      }
      this.customerInput.customerSourceId = this.customerInput.customerSource ? (this.customerInput.customerSource[1] || this.customerInput.customerSource[0]) : '';
      this.customerInput.followUpEmployeeId = this.employeeid ? this.employeeid : this.customerInput.followUpEmployeeId;
      this.customerInput.isCustomerPool = this.hasFollow;
      this.$refs.customerInput.validate(valid => {
        if (valid) {
          this.$emit('addCustomer', this.customerInput);
          // console.log(this.customerInput);
        } else {
          return false;
        }
      });
    },
    // 删除跟进人
    closeSource() {
      this.followUp = {};
      this.customerInput.followUpEmployeeId = '';
      this.customerInput.followUpName = '';
    },
    openDialog() {
      this.$refs.addFollow.followDialogVisible = true;
    },
    // 获取静态文件
    getStaticPhotoUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    cancelDialog() {
      this.id = '';
      this.dialogVisible = false;
      this.customerInput = new SaveCustomerInput();
    },
    onChangeNationality () {
      this.customerInput.national = '';
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper () {
      if (this.customerInput['imagePath']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticPhotoUrl(this.customerInput['imagePath']));
      }
      this.photoCropperVisible = true;
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.customerInput, 'imagePath', res.tempUrl);
        this.photoCropperVisible = false;
      });
    },
    // 分页
    changePage(page) {
      this.getFollowPerson(page);
    },
    changePageSize(pagesize) {
      this.customerInput.MaxResultCount = pagesize;
      this.getFollowPerson();
    }
  }
};
</script>

<style lang="scss" scoped>
.upload_game_img.no_pointer {
  cursor: default;
}
.upload_game_img {
  width: 100px;
  height: 140px;
  line-height: 140px;
  text-align: center;
  font-size: 20px;
  border: 1px dotted #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  margin: 10px 0;
}
.upload_game_img .show_img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  vertical-align: middle;
}
</style>
